import { ref } from 'vue'
import { API_BASE_URL } from '../config'

// 创建响应式登录状态
export const isLoggedIn = ref(false)

// 请求拦截器
export const request = async (url, options = {}) => {
  const token = localStorage.getItem('token')
  
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
      ...(token && { 'Authorization': `Bearer ${token}` }),
      ...options.headers
    }
  }
  
  const fullUrl = url.startsWith('http') ? url : `${API_BASE_URL}${url}`
  
  try {
    const response = await fetch(fullUrl, {
      ...defaultOptions,
      ...options
    })
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(errorData.message || `HTTP error! status: ${response.status}`)
    }
    
    return await response.json()
  } catch (error) {
    console.error('Request failed:', error)
    throw error
  }
}

// 检查登录状态
export const checkLoginStatus = () => {
  const token = localStorage.getItem('token')
  isLoggedIn.value = !!token
  return isLoggedIn.value
}

// 获取token
export const getToken = () => {
  return localStorage.getItem('token')
}

// 清除token
export const clearToken = () => {
  localStorage.removeItem('token')
  isLoggedIn.value = false
}